package com.example.demo.common;



import javax.mail.*;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

/**
 * 发送邮箱验证码工具类
 */

public class EmailUtil {
    //qq邮箱的发送邮件
    public static boolean sendMail(String to,String text,String title){
        final String USER ="2029889073@qq.com";
        final String PASSWORD = "sluuvypblmzvecia";

        try {
            Properties properties = new Properties();
            properties.put("mail.smtp.auth","true");

            properties.put("mail.smtp.host","smtp.qq.com");


            properties.put("mail.user",USER);
            properties.put("mail.password",PASSWORD);

            Authenticator authenticator = new Authenticator() {
                @Override
                protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    String userName = properties.getProperty("mail.user");
                    String password = properties.getProperty("mail.password");

                    return new PasswordAuthentication(userName,password);
                }
            };
            Session mailSession = Session.getInstance(properties,authenticator);

            MimeMessage message = new MimeMessage(mailSession);

            String username = properties.getProperty("mail.user");
            InternetAddress from = new InternetAddress(username);
            message.setFrom(from);


            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件的标题
            message.setSubject(title);
            // 设置邮件内容
            message.setContent(text, "text/html; charset = utf8");
            // 发送邮件
            Transport.send(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) {
        Random random = new Random();
        int code = random.nextInt(10_00000-100000)+100000;//随机生成验证码
        System.out.println(code);
        EmailUtil.sendMail("2029889073@qq.com","你得到的验证码为："+code +",请勿泄露和转发","欢迎您注册Sunlight的博客网站");
        System.out.println("发送成功");
    }
}
